import router from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { getRoutes } from '@/api/user'
import Vue from 'vue'

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

// 全局变量 配置
const config = {}
config.version = '1.0.0-20210304'
config.companyName = ''
Vue.prototype.config = config

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      const hasLoaded = store.getters.loaded
      if (hasLoaded) {
        next()
      } else {
        try {
          let rederictModle = ''
          if (to.path) {
            if (to.path.indexOf('/sys') > -1) {
              rederictModle = 'Sys'
            } else if (to.path.indexOf('/edu') > -1) {
              rederictModle = 'Edu'
            }
          }
          console.log(rederictModle)
          await store.dispatch('permission/setRederictModule', rederictModle)

          const res = await getRoutes()
          // console.log(res)
          const asyncRouter = res.routes || []
          await store.dispatch('user/setUserInfo', res)
          const accessRoutes = await store.dispatch('permission/generateRoutes', asyncRouter)
          // add 404 page last
          accessRoutes.push({
            path: '*',
            redirect: '/404',
            hidden: true
          })
          // console.log(accessRoutes)
          // dynamically add accessible routes
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({
            ...to,
            replace: true
          })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || '读取用户限信息错误！')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
